package com.software.loginregister.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.software.loginregister.api.UserApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.User;
import com.software.loginregister.LoginActivity;
import com.software.loginregister.R;
import com.software.loginregister.util.RetrofitClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends AppCompatActivity {
    private EditText edtUsername, edtPassword, edtConfirmPassword, edtPhone, edtEmail;
    private Button btnRegister;
    private TextView tvToLogin;
    private UserApi userApi;
    private ImageView ivPasswordVisibility;
    private ImageView ivConfirmPasswordVisibility;
    private boolean isPasswordVisible = false;
    private boolean isConfirmPasswordVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // 设置沉浸式状态栏
        setStatusBar();

        // 初始化视图
        initViews();
        // 获取API实例
        userApi = RetrofitClient.getInstance().create(UserApi.class);
        // 初始化点击事件
        initListeners();
    }

    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }
    // 添加切换密码可见性的方法
    private void togglePasswordVisibility(EditText editText, ImageView imageView, boolean isPassword) {
        if (isPassword) {
            isPasswordVisible = !isPasswordVisible;
        } else {
            isConfirmPasswordVisible = !isConfirmPasswordVisible;
        }

        boolean isVisible = isPassword ? isPasswordVisible : isConfirmPasswordVisible;

        if (isVisible) {
            // 显示密码
            editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            imageView.setImageResource(R.drawable.ic_password_visible);
        } else {
            // 隐藏密码
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            imageView.setImageResource(R.drawable.ic_password_invisible);
        }

        // 将光标移到文本末尾
        editText.setSelection(editText.getText().length());
    }

    private void initViews() {
        edtUsername = findViewById(R.id.edt_register_username);
        edtPassword = findViewById(R.id.edt_register_password);
        edtConfirmPassword = findViewById(R.id.edt_confirm_password);
        edtEmail = findViewById(R.id.edt_email);  // 添加邮箱输入框绑定
        edtPhone = findViewById(R.id.edt_phone);
        btnRegister = findViewById(R.id.btn_register);
        tvToLogin = findViewById(R.id.tv_to_login);
    }

    private void initListeners() {
        btnRegister.setOnClickListener(v -> performRegister());
        tvToLogin.setOnClickListener(v -> {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        });
    }

    private void performRegister() {
        String username = edtUsername.getText().toString().trim();
        String password = edtPassword.getText().toString().trim();
        String confirmPassword = edtConfirmPassword.getText().toString().trim();
        String phone = edtPhone.getText().toString().trim();
        String email = edtEmail.getText().toString().trim();  // 获取邮箱输入

        // 输入验证
        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "请填写必要信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        // 如果输入了邮箱，验证邮箱格式
        if (!email.isEmpty() && !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(this, "请输入正确的邮箱格式", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建用户对象
        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        if (!phone.isEmpty()) {
            user.setPhone(phone);
        }

        if (!email.isEmpty()) {
            user.setEmail(email);  // 设置邮箱，需要确保 User 类中有 email 字段
        }


        Log.d("RegisterDebug", "正在尝试连接服务器: " + RetrofitClient.BASE_URL);

        userApi.register(user).enqueue(new Callback<Result<String>>() {
            @Override
            public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                try {
                    Log.d("RegisterDebug", "收到服务器响应: " + response.code());

                    if (response.isSuccessful() && response.body() != null) {
                        Result<String> result = response.body();
                        Log.d("RegisterDebug", "响应code: " + result.getCode());
                        Log.d("RegisterDebug", "响应message: " + result.getMsg());
                        Log.d("RegisterDebug", "响应data: " + result.getData());

                        if (result.getCode() == 200 || result.getCode() == 1) {
                            Log.d("RegisterDebug", "注册成功");

                            runOnUiThread(() -> {
                                Toast.makeText(RegisterActivity.this,
                                        "注册成功", Toast.LENGTH_SHORT).show();
                                // 注册成功后跳转到登录页
                                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                // 可以把用户名传递给登录页面
                                intent.putExtra("username", username);
                                startActivity(intent);
                                finish();
                            });
                        } else {
                            String errorMsg = result.getMsg();
                            Log.d("RegisterDebug", "注册失败: " + errorMsg);
                            runOnUiThread(() -> {
                                Toast.makeText(RegisterActivity.this,
                                        errorMsg != null ? errorMsg : "注册失败",
                                        Toast.LENGTH_SHORT).show();
                            });
                        }
                    } else {
                        runOnUiThread(() -> {
                            Toast.makeText(RegisterActivity.this,
                                    "注册失败: " + response.message(),
                                    Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    Log.e("RegisterDebug", "注册处理出错", e);
                    runOnUiThread(() -> {
                        Toast.makeText(RegisterActivity.this,
                                "注册处理出错: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    });
                }
            }

            @Override
            public void onFailure(Call<Result<String>> call, Throwable t) {
                Log.e("RegisterDebug", "网络请求失败", t);
                runOnUiThread(() -> {
                    Toast.makeText(RegisterActivity.this,
                            "网络错误: " + t.getMessage(),
                            Toast.LENGTH_LONG).show();
                });
            }
        });
    }
}